package com.stx.jeepay.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.stx.jeepay.core.dao.SysConfigDao;
import com.stx.jeepay.core.entity.SysConfigEntity;
import com.stx.jeepay.core.model.DBApplicationConfig;
import com.stx.jeepay.core.service.SysConfigService;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Set;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;


@Service("sysConfigService")
public class SysConfigServiceImpl extends ServiceImpl<SysConfigDao, SysConfigEntity> implements SysConfigService {

    /**
     * 是否启用缓存
     * true: 表示将使用内存缓存， 将部分系统配置项 或 商户应用/服务商信息进行缓存并读取
     * false: 直接查询DB
     **/
    public static boolean IS_USE_CACHE = false;

    /**
     * 数据库application配置参数
     **/
    private static MutablePair<String, DBApplicationConfig> APPLICATION_CONFIG = new MutablePair<>("applicationConfig", null);

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateByConfigKey(Map<String, String> updateMap) {

        int count = 0;
        Set<String> set = updateMap.keySet();
        for (String key : set) {
            SysConfigEntity sysConfig = new SysConfigEntity();
            sysConfig.setConfigKey(key);
            sysConfig.setConfigVal(updateMap.get(key));
            boolean result = saveOrUpdate(sysConfig);
            if (result) {
                count++;
            }
        }
        return count;
    }

    /**
     * 数据库application配置参数
     *
     * @param groupKey
     */
    @Override
    public synchronized void initDBConfig(String groupKey) {
        // 若当前系统不缓存，则直接返回
        if (!IS_USE_CACHE) {
            return;
        }

        if (APPLICATION_CONFIG.getLeft().equalsIgnoreCase(groupKey)) {
            APPLICATION_CONFIG.right = this.selectByGroupKey(groupKey).toJavaObject(DBApplicationConfig.class);
        }
    }

    /** 获取实际的数据 **/
    @Override
    public DBApplicationConfig getDBApplicationConfig() {
        // 查询DB
        if (!IS_USE_CACHE){
            return this.selectByGroupKey(APPLICATION_CONFIG.getLeft()).toJavaObject(DBApplicationConfig.class);
        }

        // 缓存数据
        if(APPLICATION_CONFIG.getRight() == null ){
            initDBConfig(APPLICATION_CONFIG.getLeft());
        }
        return APPLICATION_CONFIG.right;
    }

    /**
     * 根据分组查询，并返回JSON对象格式的数据
     **/
    public JSONObject selectByGroupKey(String groupKey) {
        JSONObject result = new JSONObject();
        list(new LambdaQueryWrapper<SysConfigEntity>()
                .select(SysConfigEntity::getConfigKey, SysConfigEntity::getConfigVal)
                .eq(SysConfigEntity::getGroupKey, groupKey))
                .stream().forEach(i -> result.put(i.getConfigKey(), i.getConfigVal()));
        return result;
    }
}